package com.hqsj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.sd4324530.fastweixin.api.CustomAPI;
import com.github.sd4324530.fastweixin.api.MaterialAPI;
import com.github.sd4324530.fastweixin.api.UserAPI;
import com.github.sd4324530.fastweixin.api.entity.UserInfo;
import com.github.sd4324530.fastweixin.api.entity.UserRead;
import com.github.sd4324530.fastweixin.api.enums.MaterialType;
import com.github.sd4324530.fastweixin.api.response.*;
import com.github.sd4324530.fastweixin.message.Article;
import com.hqsj.service.MaterialService;
import com.hqsj.thread.SendCustomMsgThread;
import com.hqsj.thread.SendMpNewsMsgThread;
import com.hqsj.util.JSONUtil;
import com.hqsj.util.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.UnaryOperator;

/**
 * Created by huangying on 2017/4/14.
 */
@RestController
@RequestMapping("weixin")
public class WeixinController {

    @RequestMapping("login")
    public JSONObject login(@RequestBody String body) {

        GetUserInfoResponse user = userAPI.getUserInfo("oy2qbv3OxU3SgdGr_1Sf-AoLvk80");

        System.out.println("怎么我也要打印：" + JSONUtil.toJsonStr(user));

        if (null != user && user.getErrcode() == null && user.getSubscribe() == 1 && user.getNickname().equals("黄蓥")) {
            System.out.println(JSONUtil.toJsonStr(user));
        }

        String[] strings = null;
        if(null != strings && strings.length == 1) {
            System.out.println("strings 长度为1");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success", false);
        if ("".equals(body.trim()) || null == body) {
            jsonObject.put("msg", "登录请求为空，登录失败");
            return jsonObject;
        }

        JSONObject requestParams = JSON.parseObject(body);
        String username = requestParams.getString("username");
        String password = requestParams.getString("password");
        if ("yangfengmai".equals(username.trim()) && "yfm147258".equals(password.trim())) {
            jsonObject.put("success", true);
            jsonObject.put("msg", "登录成功");
            jsonObject.put("username", username);
            return jsonObject;
        } else if ("huangying".equals(username.trim()) && "hyl12138".equals(password.trim())) {
            jsonObject.put("success", true);
            jsonObject.put("msg", "登录成功");
            jsonObject.put("username", username);
            return jsonObject;
        } else {
            jsonObject.put("msg", "密码错误或者用户不存在，登录失败");
            return jsonObject;
        }
    }

    @RequestMapping("fetch_news")
    public GetMaterialListResponse fetchNews(
            HttpServletResponse response,
            @RequestParam("_page") int page,
            @RequestParam("_limit") int pageSize) {

//        response.setHeader("x-total-count", String.valueOf(materialAPI.countMaterial().getNews()));

        GetMaterialListResponse getMaterialListResponse = materialAPI.batchGetMaterial(MaterialType.NEWS, page * pageSize, pageSize);
//        System.out.println(JSONUtil.toJsonStr(getMaterialListResponse));
        return getMaterialListResponse;

    }

    @PostMapping("fetch_news_by_media_id")
    public JSONObject fetchNewsByMediaId(@RequestBody String mediaIds) {
//        System.out.println(mediaIds);
        JSONObject jsonObject = new JSONObject();
        JSONArray items = new JSONArray();
        List<String> list = JSONUtil.toList(mediaIds, String.class);
        if (list.size() == 0) {
            jsonObject.put("total", 0);
        } else {
            int count = 0;
            for (int i = 0; i < list.size(); i++) {
                DownloadMaterialResponse downloadMaterialResponse = materialAPI.downloadMaterial(list.get(i), MaterialType.NEWS);
//                System.out.println("downloadMaterialResponse===" + JSONUtil.toJsonStr(downloadMaterialResponse));
                if (downloadMaterialResponse.getNews() != null) {
                    JSONObject news = new JSONObject();
//                    System.out.println(JSONUtil.toJsonStr(downloadMaterialResponse.getNews()));
                    news.put("media_id", list.get(i));
                    news.put("content", downloadMaterialResponse.getNews());
                    items.add(news);
                    count++;
                }
            }
            jsonObject.put("total", count);
        }
        jsonObject.put("items", items);
//        System.out.println(jsonObject);
        return jsonObject;
    }

    @RequestMapping("get_users")
    public GetUsersResponse getUsers(
            @RequestParam("_next_openid") String nextOpenid ) {
//        System.out.println("nextOpenid=" + nextOpenid);
        GetUsersResponse getUsersResponse = userAPI.getUsers(nextOpenid);
        return getUsersResponse;
    }

    @PostMapping("get_user_info_list")
    public GetUserInfoListResponse getUserInfoList(@RequestBody String openidListStr) {
//        System.out.println(openidListStr);

        List<UserInfo> userInfoList = JSONUtil.toList(openidListStr, UserInfo.class);

//        GetUsersResponse getUsersResponse = userAPI.getUsers("");
//        List<UserInfo> list = new ArrayList<>();
//        for(String s: getUsersResponse.getData().getOpenid()) {
//            list.add(new UserInfo(s));
//        }
        GetUserInfoListResponse getUserInfoListResponse = userAPI.getUserInfoList(userInfoList);

//        System.out.println(getUserInfoListResponse);

        return getUserInfoListResponse;
    }

    @PostMapping("send_custom_msg")
    public JSONObject sendTemplateMsg(@RequestBody String body) {
//        System.out.println(body);

//        System.out.println(body);
        JSONObject returnObj = new JSONObject();
        returnObj.put("success", false);

        JSONObject jsonObject = (JSONObject) JSON.parse(body);
        String mediaId = jsonObject.getString("mediaId");
        long beginTime = jsonObject.getLong("beginTime");
        long endTime = jsonObject.getLong("endTime");

        if (beginTime * 1000 > new Date().getTime()) {
            returnObj.put("msg", "开始时间必须小于当前时间");
            return returnObj;
        }

//        if (endTime * 1000 > new Date().getTime()) {
//            returnObj.put("msg", "结束时间必须小于当前时间");
//            return returnObj;
//        }

        if (beginTime >= endTime) {
            returnObj.put("msg", "开始时间必须小于结束时间");
            return returnObj;
        }

        if (mediaId == null || "".equals(mediaId.trim())) {
            returnObj.put("msg", "mediaId不能为空");
            return returnObj;
        }

//        System.out.println(mediaId);
//        System.out.println(beginTime);
//        System.out.println(endTime);
        //发送客服消息
//        new SendCustomMsgThread(mediaId, beginTime, endTime, userAPI, customAPI, materialAPI).start();
        new SendMpNewsMsgThread(mediaId, beginTime, endTime, userAPI, customAPI, materialAPI).start();

        returnObj.put("success", true);
        returnObj.put("msg", "请求成功，后台正在发送模版消息～");
        return returnObj;
    }

    @Autowired
    MaterialAPI materialAPI;

    @Autowired
    UserAPI userAPI;

    @Autowired
    CustomAPI customAPI;

    @Autowired
    MaterialService materialService;

}
